// 业务逻辑区（原有功能保持不变）
const socket = io();
const currentUserId = localStorage.getItem('userId');
const currentNickname = localStorage.getItem('nickname');
if (!currentUserId) {
  console.error('用户未登录，无法加载聊天界面');
  window.location.href = 'index.html'; // 重定向到登录页
} else {
  // 发送上线事件,让服务器将 socket 加入对应房间
  socket.emit('online', {
    userId: currentUserId,
    nickname: currentNickname
  });
}

const currentUserAvatar   = localStorage.getItem('avatar') || 'upload/images/default_head.jpg';
const chatPartnerId = localStorage.getItem('chatFriendId');
const chatPartnerNickname = localStorage.getItem('chatFriendNickname');
const chatPartnerAvatar   = localStorage.getItem('chatFriendAvatar') || 'upload/images/default_head.jpg';

// 按 userId 快速取头像
const avatarMap = {
  [currentUserId]: currentUserAvatar,
  [chatPartnerId]: chatPartnerAvatar
};

// 记录上一次渲染的消息发送者，用于合并连续消息
let lastMessageSender = null;

document.getElementById('chatWithNickname').textContent = chatPartnerNickname;
const chatBox = document.getElementById('chatList');
const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('send-btn');

// 限制输入框最大长度
messageInput.maxLength = 200; // HTML 层级限制

// 输入事件监听，确保不超过最大长度
messageInput.addEventListener('input', (e) => {
  const maxLength = 200;
  if (e.target.value.length > maxLength) {
    e.target.value = e.target.value.slice(0, maxLength);
  }
});

window.addEventListener('DOMContentLoaded', () => {
  loadChatHistory(currentUserId, chatPartnerId, chatBox);
  socket.emit('joinPrivateChat', { userId: currentUserId, partnerId: chatPartnerId });
});

sendBtn.addEventListener('click', () => {
  const content = messageInput.value.trim();
  if (!content || content.length > 200) return; // 添加长度检查
  const msgData = {
    senderId: currentUserId,
    receiverId: chatPartnerId,
    content,
    mode: 'real',
  };
  socket.emit('sendMessage', msgData);
  appendMessage({ content }, true);
  messageInput.value = '';
});

socket.on('newMessageNotice', async ({ from }) => {
  if (from !== chatPartnerId) return;
  try {
    const res = await axios.get('/api/chat/history', {
      params: { userId: currentUserId, partnerId: chatPartnerId }
    });
    chatBox.innerHTML = '';
    res.data.forEach(msg => appendMessage(msg, msg.senderId === currentUserId));
  } catch (err) {
    console.error('拉取消息失败:', err);
  }
});

// 极致特效 & 时间戳渲染
function appendMessage(message, fromSelf = false) {
  // 防重渲染
  if (message.messageId && document.querySelector(`[data-msg-id="${message.messageId}"]`)) {
    return;
  }

  const senderId = message.senderId || (fromSelf ? currentUserId : chatPartnerId);
  const showAvatar = senderId !== lastMessageSender;

  // 创建聊天项
  const li = document.createElement('li');
  li.className = `chat-item ${fromSelf ? 'self' : 'other'}`;
  if (message.messageId) li.dataset.msgId = message.messageId;


  // 构建头像（仅在需要时插入）
  // if (showAvatar) {
  const avatarEl = document.createElement('img');
  avatarEl.className = 'msg-avatar';
  avatarEl.src       = avatarMap[senderId];
  avatarEl.alt       = '头像';
  avatarEl.style.visibility = showAvatar ? 'visible' : 'hidden';
  // 对方消息在左，自身消息在右
  li.appendChild(avatarEl);
  lastMessageSender = senderId;
  // }

  const bubble = document.createElement('div');
  bubble.className = 'msg-bubble';

  const content = document.createElement('div');
  content.className = 'msg-content';
  content.textContent = message.content;

  const time = document.createElement('div');
  time.className = 'msg-time';
  const ts = message.timestamp ? new Date(message.timestamp) : new Date();
  
  // 判断是否是当天的消息
  const today = new Date();
  const isToday = ts.getDate() === today.getDate() && 
                  ts.getMonth() === today.getMonth() &&
                  ts.getFullYear() === today.getFullYear();
  
  // 根据是否是当天使用不同的时间格式
  time.textContent = isToday 
    ? ts.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    : `${ts.getMonth() + 1}月${ts.getDate()}日 ${ts.toLocaleTimeString([], {
        hour: '2-digit',
        minute: '2-digit'
      })}`;

  bubble.append(content, time);
  li.appendChild(bubble);
  chatBox.appendChild(li);

  // 入场动画
  anime({
    targets: li,
    opacity: [0, 1],
    translateY: [20, 0],
    duration: 400,
    easing: 'easeOutExpo'
  });

  // 滚动到底部
  chatBox.scrollTo({ top: chatBox.scrollHeight, behavior: 'smooth' });
}

async function loadChatHistory(currentUserId, chatPartnerId, chatBox) {
  chatBox.innerHTML = '<div class="loader"></div>';
  try {
    const res = await axios.get('/api/chat/history', {
      params: { userId: currentUserId, partnerId: chatPartnerId }
    });
    chatBox.innerHTML = '';
    lastMessageSender = null;  // ← 关键：清空上次记录

    res.data.forEach(msg => appendMessage(msg, msg.senderId === currentUserId));
  } catch (err) {
    chatBox.innerHTML = `<p class="error">❌ 加载失败：${err.message}</p>`;
    console.error('拉取聊天记录出错：', err);
  }
}

// 顶部按钮预留
document.getElementById('back-btn').addEventListener('click', () => history.back());
document.getElementById('settings-btn').addEventListener('click', async () => {
  const modal = document.getElementById('settingsModal');
  const friendId = localStorage.getItem('chatFriendId');
  
  try {
    // 获取好友信息
    const response = await axios.get(`/api/user/profile/${friendId}`);
    const friendData = response.data;
    
    // 填充模态框
    document.getElementById('friendAvatar').src = friendData.avatar;
    document.getElementById('friendNickname').textContent = friendData.nickname;
    document.getElementById('friendUserId').textContent = friendData.userId;
    document.getElementById('friendEmail').textContent = friendData.email;
    document.getElementById('friendGender').innerHTML = friendData.gender === '男' ? 
      '<i class="fas fa-mars"></i>' : 
      friendData.gender === '女' ? 
      '<i class="fas fa-venus"></i>' : 
      '<i class="fas fa-genderless"></i>';
    document.getElementById('friendBio').textContent = friendData.bio || '这个人很懒，什么都没写~';
    
    // 获取并填充备注
    const remark = await axios.get(`/api/friend/get-remark`, {
      params: { userId: localStorage.getItem('userId'), friendId: localStorage.getItem('chatFriendId') }
    });
    // const friend = userResponse.data.friends.find(f => f.userId === friendId);
    document.getElementById('remarkInput').value = remark?.data.remark || localStorage.getItem('chatFriendNickname');

    modal.style.display = 'block';
  } catch (error) {
    console.error('获取好友信息失败:', error);
  }
});

// 关闭模态框
document.querySelector('.close-btn').addEventListener('click', () => {
  document.getElementById('settingsModal').style.display = 'none';
});

// 保存备注
document.getElementById('saveRemark').addEventListener('click', async () => {
  const remark = document.getElementById('remarkInput').value.trim();
  const friendId = localStorage.getItem('chatFriendId');
  
  try {
    await axios.post('/api/friend/set-remark', {
      userId: localStorage.getItem('userId'),
      friendId,
      remark
    });
    
    // 更新聊天室顶部显示
    const nickname = document.getElementById('chatWithNickname');
    nickname.textContent = remark || localStorage.getItem('chatFriendNickname');
    
    // 关闭模态框
    document.getElementById('settingsModal').style.display = 'none';
  } catch (error) {
    console.error('设置备注失败:', error);
  }
});

// 粒子背景初始化
window.addEventListener('load', () => {
  if (window.tsParticles && tsParticles.load) {
    tsParticles.load('tsparticles', {
      fpsLimit: 60,
      background: { color: 'transparent' },
      particles: {
        number: { value: 60, density: { enable: true, area: 800 } },
        color: { value: ['#ffa7c4', '#fff3a8'] },
        shape: { type: 'circle' },
        opacity: { value: 0.5, random: { enable: true, minimumValue: 0.3 } },
        size: { value: { min: 1, max: 4 } },
        move: { enable: true, speed: 1, outModes: { default: 'out' } }
      },
      interactivity: {
        events: {
          onHover: { enable: true, mode: 'repulse' },
          onClick: { enable: true, mode: 'push' }
        },
        modes: { repulse: { distance: 100 }, push: { quantity: 4 } }
      },
      detectRetina: true
    });
  } else {
    console.error('tsParticles 未加载，全屏粒子效果跳过');
  }
});

// 在页面加载时添加
window.addEventListener('DOMContentLoaded', async () => {
  // 标记所有来自当前聊天对象的消息为已读
  try {
    await axios.put('/api/chat/read', {
      senderId: chatPartnerId,
      receiverId: currentUserId
    });
    console.log('标记已读成功');
    // 更新未读消息数
  } catch (err) {
    console.error('标记已读失败:', err);
  }
});

// 常用 emoji 列表
const commonEmojis = [
  '😀', '😂', '🥰', '😊', '😎', '🤔', '😴', '😭',
  '👋', '👍', '👎', '❤️', '💔', '🌹', '🎉', '✨',
  '🌞', '🌙', '☔', '⭐', '🔥', '🎵', '🎮', '🍕'
];

// 初始化 emoji 选择器
const emojiBtn = document.getElementById('emoji-btn');
const emojiPicker = document.getElementById('emoji-picker');

// 创建 emoji 选择器内容
commonEmojis.forEach(emoji => {
  const span = document.createElement('span');
  span.className = 'emoji-item';
  span.textContent = emoji;
  span.onclick = () => {
    messageInput.value += emoji;
    messageInput.focus();
    emojiPicker.style.display = 'none';
  };
  emojiPicker.appendChild(span);
});

// 切换 emoji 选择器显示
emojiBtn.onclick = (e) => {
  e.stopPropagation();
  emojiPicker.style.display = emojiPicker.style.display === 'none' ? 'grid' : 'none';
};

// 点击其他地方关闭选择器
document.addEventListener('click', (e) => {
  if (!emojiPicker.contains(e.target) && e.target !== emojiBtn) {
    emojiPicker.style.display = 'none';
  }
});

// 防止选择器内部点击事件冒泡
emojiPicker.onclick = (e) => {
  e.stopPropagation();
};

window.addEventListener('beforeunload', () => {
  socket.emit('leavePrivateChat', { userId, partnerId });
});

async function setChatroomBackground() {
  const userId = localStorage.getItem('userId');
  try {
    const res = await axios.get(`/api/user/profile/${userId}`);
    const bg = res.data.backgroundImage;
    const bgDiv = document.querySelector('.background');
    if (bg && bg.trim()) {
      bgDiv.style.background = `url('${bg}') center center/cover no-repeat`;
    } else {
      // 保持原有渐变
      bgDiv.style.background = '';
    }
  } catch (e) {
    // 保持原有渐变
  }
}
setChatroomBackground();
